<template>
  <el-dialog
    ref="drawerRef"
    v-model="dialog"
    title="入库"
    :before-close="handleClose"
    direction="rtl"
    :with-header="true"
    class="demo-drawer"
    width="80%"
    v-loading="loading"
  >
    <!-- <div class="heads">
      <el-button type="primary" v-if="!companySelect" text @click="addCompany()">添加企业信息</el-button>
    </div> -->
    <div class="demo-drawer__content">
      <el-form :model="formData" :inline="true">
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-select v-model="formData.bill_type" placeholder="请选择">
            <el-option v-for="item in bill_type_options" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业:" :label-width="formLabelWidth">
          <el-autocomplete
            :disabled="true"
            v-model="state"
            :fetch-suggestions="querySearchAsync"
            value-key="company_name"
            placeholder="请输入"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="业务员" :label-width="formLabelWidth">
          <el-select v-model="uid" placeholder="请选择" :disabled="true">
            <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider />
      <div class="row">
        <div class="block">
          <span class="block_title">先款先票：</span>
          <el-radio-group v-model="formData.enter_checks">
            <el-radio v-for="option in checkList" :key="option.data_value" :label="Number(option.data_value)">
              {{ option.data_name }}
            </el-radio>
          </el-radio-group>
        </div>
        <div class="block">
          <span class="block_title">开票：</span>
          <el-radio-group v-model="formData.enter_invoicings">
            <el-radio v-for="option in invoicingList" :key="option.data_value" :label="Number(option.data_value)">
              {{ option.data_name }}
            </el-radio>
          </el-radio-group>
        </div>
        <div class="block">
          <span class="block_title">入库时间：</span>
          <el-date-picker
            v-model="formData.enter_time"
            style="width: 100%"
            type="datetime"
            placeholder="请选择入库时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
      </div>
      <el-descriptions title="票据信息" size="small" :column="3" border>
        <template #extra>
          <el-text class="mx-1" type="danger">如若是老票,或是不可拆份票据,子票区间都为0</el-text>
        </template>
        <el-descriptions-item label="日期">{{ formData.recognizerDate }}</el-descriptions-item>
        <el-descriptions-item label="票号">{{ formData.billNo }}</el-descriptions-item>
        <el-descriptions-item label="承兑人">{{ formData.acceptorName }}</el-descriptions-item>
        <el-descriptions-item label="到期日">{{ formData.expirationDate }}</el-descriptions-item>
        <el-descriptions-item label="背书人">{{ formData.bill_back_user }}</el-descriptions-item>
        <el-descriptions-item label="是否为瑕疵票">{{ formData.is_flaw == 1 ? "否" : "是" }}</el-descriptions-item>
        <el-descriptions-item label="票面金额(万元)">{{ formData.billAmount }}</el-descriptions-item>
        <el-descriptions-item label="子票开始区间">{{ formData.billRangeLower }}</el-descriptions-item>
        <el-descriptions-item label="子票开始区间">{{ formData.billRangeUpper }}</el-descriptions-item>
        <el-descriptions-item label="每十万价格">
          <el-input v-model="moneys" type="number" min="1" placeholder="请输入" clearable @input="change" />
        </el-descriptions-item>
        <el-descriptions-item label="贴息价格">
          <el-input
            v-model="discountMoney"
            type="number"
            min="1"
            placeholder="请输入"
            clearable
            @input="discountChange"
          />
        </el-descriptions-item>
        <el-descriptions-item label="实付金额">
          <el-input
            v-model="formData.money"
            type="number"
            min="1"
            placeholder="请输入"
            clearable
            @input="handleFinally"
          />
        </el-descriptions-item>
        <el-descriptions-item label="备注">
          <el-input v-model="formData.remark" autosize type="textarea" placeholder="请输入" clearable />
        </el-descriptions-item>
        <!-- <el-descriptions-item label="实付金额">{{ formData.money }}</el-descriptions-item> -->
      </el-descriptions>
      <div class="demo-drawer__footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="onClick">提交</el-button>
      </div>

      <price ref="priceRef" />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue"
// import { computed, reactive, ref } from "vue"
import { ElDrawer, ElMessage } from "element-plus"
import price from "./price.vue"
import { companyListApi, dictDataGetListApi } from "@/api/conventional"
// import { GetListsResponseData } from "@/api/system/types/admin"
import { getAdminRoleListApi } from "@/api/system"
import { doWarehouseEditApi } from "@/api/billv2"
// import { doWarehouseEditApi } from "@/api/bill"
import { generateDiscount, generatePrice } from "@/utils/common"
import Decimal from "decimal.js"

const formLabelWidth = "80px"

const dialog = ref(false)
const loading = ref(false)
const buttonLoading = ref(false)
const priceRef = ref<any>()
const listData = ref<any>([])
// const listLog = ref<GetBillLogTableData[]>([])
const state = ref("")
const uid = ref<number>(0)
const company_id = ref<number>(0)

// const addCompany = () => {
//   if (priceRef.value) {
//     priceRef.value.show()
//   }
// }
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      console.log("getAdminRoleListApi")
      console.log(res)
      listData.value = res.data
      console.log("getAdminRoleListApi")
      console.log(listData)
    })
    .catch(() => {})
    .finally(() => {})
}
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  state.value = queryString
  companyListApi({
    company_name: state.value
  }).then((res) => {
    const lists = res.data
    if (lists.length == 0) {
      ElMessage.error("请先添加企业信息")
      cb([])
    } else {
      cb(lists)
    }
  })
}

const handleSelect = (item: any) => {
  console.log("value")
  console.log(item)
  uid.value = item.uid
  company_id.value = item.id
}

const companyLists = async () => {
  const data = await companyListApi({
    company_name: state.value
  })
  const lists = data.data
  if (lists.length == 0) {
    ElMessage.error("请先添加企业信息")
    return []
  }
  return lists
}

const moneys = ref<number>(0)
const discountMoney = ref<number>(0)
const bill_type_options = ref([
  { id: 1, label: "贴现" },
  { id: 2, label: "买票" }
])
const formData = reactive({
  bill_type: 1,
  bill_id: 0,
  recognizerDate: "",
  billNo: "",
  acceptorName: "",
  billAmount: 0,
  price: 0,
  money: 0,
  moneys: 0,
  expirationDate: "",
  billRangeUpper: "",
  billRangeLower: "",
  is_flaw: 1,
  enter_checks: 2,
  enter_invoicings: 2,
  bill_back_user: "",
  remark: "",
  enter_time: ""
})

const drawerRef = ref<InstanceType<typeof ElDrawer>>()
const onClick = async () => {
  // if (company_id.value != "") {
  //   ElMessage.warning("请先添加当前客户")
  //   return
  // }
  buttonLoading.value = true
  await doWarehouseEditApi({
    bill_id: formData.bill_id,
    bill_type: formData.bill_type,
    enter_invoicings: formData.enter_invoicings,
    enter_checks: formData.enter_checks,
    enter_price: moneys.value || undefined,
    enter_discount: discountMoney.value || undefined,
    enter_finally: formData.money || undefined,
    remark: formData.remark || undefined,
    enter_time: formData.enter_time || undefined
  })
  buttonLoading.value = false
  ElMessage.success("修改成功")
  handleClose()
}
const dialogShow = async (row: any) => {
  dialog.value = true

  companySelect.value = false
  formData.bill_id = row.bill_id
  formData.recognizerDate = row.recognizerDate
  formData.billNo = row.billNo
  formData.acceptorName = row.acceptorName
  formData.billAmount = parseFloat(row.billAmount)
  formData.expirationDate = row.expirationDate
  formData.bill_back_user = row.bill_back_user
  formData.is_flaw = row.is_flaw
  formData.enter_invoicings = row.enter_invoicings
  formData.enter_checks = row.enter_checks
  formData.billRangeUpper = row.billRangeUpper
  formData.billRangeLower = row.billRangeLower
  formData.enter_time = row.enter_time
  state.value = row.bill_back_user
  moneys.value = row.enter_price
  discountMoney.value = row.enter_discount
  formData.money = row.enter_finally
  formData.remark = row.remark

  const companyData = await companyLists()
  if (companyData?.length == 1) {
    company_id.value = companyData[0].id
    uid.value = companyData[0].uid
    companySelect.value = true
  }
  INVOICINGFun()
  checkFun()
  await getAdminList()
  // await getBillLogList()
}
const handleClose = () => {
  cancelForm()
  // drawerRef.value!.close()
  emit("DialogClose", true)
}
const emit = defineEmits(["DialogClose"])
const cancelForm = () => {
  formData.money = 0
  uid.value = 0
  state.value = ""
  listData.value = []
  moneys.value = 0
  discountMoney.value = 0
  formData.bill_id = 0
  formData.recognizerDate = ""
  formData.billNo = ""
  formData.acceptorName = ""
  formData.billAmount = 0
  formData.expirationDate = ""
  formData.bill_back_user = ""
  formData.is_flaw = 1
  formData.billRangeUpper = ""
  formData.billRangeLower = ""
  formData.enter_time = ""
  formData.enter_invoicings = 0
  formData.enter_checks = 0
  formData.remark = ""
  buttonLoading.value = false
  loading.value = false
  dialog.value = false
}

const change = () => {
  const { finallyAmount, discountAmount } = generatePrice(
    moneys.value,
    formData.money,
    discountMoney.value,
    formData.billAmount + "",
    false
  )
  formData.money = finallyAmount
  discountMoney.value = discountAmount.toFixed(2)
}
const discountChange = () => {
  const { price, finallyAmount } = generateDiscount(
    moneys.value,
    formData.money,
    discountMoney.value,
    formData.billAmount + "",
    false
  )
  formData.money = finallyAmount
  moneys.value = price.toFixed(2)
}
const handleFinally = () => {
  const billAmount = new Decimal(formData.billAmount).times(10000)
  const enter_finally = formData.money
  const discountAmount = billAmount.minus(enter_finally).toNumber()
  console.log(discountAmount)
  const { price } = generateDiscount(moneys.value, enter_finally, discountAmount, formData.billAmount + "", false)
  moneys.value = price.toFixed(2)
  // row.enter_finally = finallyAmount
  discountMoney.value = discountAmount
}

const companySelect = ref<boolean>(false)

const invoicingList = ref<any[]>([])
const INVOICINGFun = async () => {
  const res = await dictDataGetList("COMPANY_INVOICING")
  invoicingList.value = res.data
}
const checkList = ref<any[]>([])
const checkFun = async () => {
  const res = await dictDataGetList("COMPANY_CHECK")
  checkList.value = res.data
}

const dictDataGetList = async (type: string) => {
  try {
    const res = await dictDataGetListApi({ type_code: type })
    return res
  } catch (error) {
    console.error("Error:", error)
  }
}

defineExpose({ dialogShow })
</script>

<style scoped lang="scss">
.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.heads div {
  margin-left: 10px;
}

.demo-drawer__footer {
  margin-top: 10px;
  display: flex;
  justify-content: end;
}

.logBox {
  margin-top: 20px;
}
.row {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.block {
  width: 30%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.block_title {
  width: 100px;
}
</style>
